package service

import (
	"context"
	"gitee.com/DonHz/basic-go/webook/internal/domain"
	"gitee.com/DonHz/basic-go/webook/internal/repository"
	"gitee.com/DonHz/basic-go/webook/pkg/logger"
	"golang.org/x/sync/errgroup"
)

type InteractiveService interface {
	// 阅读量
	IncrReadCnt(ctx context.Context, biz string, bizId int64) error
	// 点赞
	Like(ctx context.Context, biz string, bizId int64, uid int64) error
	// 取消点赞
	CancelLike(ctx context.Context, biz string, bizId int64, uid int64) error
	// 收藏
	Collect(ctx context.Context, biz string, bizId, cid, uid int64) error
	GetCnt(ctx context.Context, biz string, bizId, uid int64) (domain.Interactive, error)
}

type interactiveService struct {
	repo repository.InteractiveRepository
	l logger.Logger
}


func NewinteractiveService(repo repository.InteractiveRepository, l logger.Logger) InteractiveService {
	return &interactiveService{
		repo: repo,
		l: l,
	}
}

func (i *interactiveService) IncrReadCnt(ctx context.Context, biz string, bizId int64) error {
	return i.repo.IncrReadCnt(ctx, biz, bizId)
}

func (i *interactiveService) Like(ctx context.Context, biz string, bizId int64, uid int64) error {
	return i.repo.IncrLike(ctx, biz, bizId, uid)
}

func (i *interactiveService) CancelLike(ctx context.Context, biz string, bizId int64, uid int64) error {
	return i.repo.DecrLike(ctx, biz, bizId, uid)
}

func (i *interactiveService) Collect(ctx context.Context, biz string, bizId , cid, uid int64) error {
	return i.repo.AddCollectItem(ctx, biz, bizId, cid, uid)
}

func (i *interactiveService) GetCnt(ctx context.Context, biz string, bizId, uid int64) (domain.Interactive, error) {
	// 阅读、点赞、收藏量
	// 用户本身有没有点赞收藏
	var (
		eg errgroup.Group
		intr domain.Interactive
		liked bool
		collected bool
	)
	eg.Go(func() error{
		var err error
		intr, err=i.repo.Get(ctx, biz, bizId, uid)
		return err
	})
	eg.Go(func() error {
		var err error
		liked, err = i.repo.Liked(ctx, biz, bizId, uid)
		return err
	})
	eg.Go(func() error {
		var err error
		collected, err = i.repo.Collected(ctx, biz, bizId, uid)
		return err
	})
	err := eg.Wait()
	if err!=nil{
		return domain.Interactive{}, err
	}
	intr.Liked=liked
	intr.Collectd=collected
	return intr, err
}